package thread.线程池;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoll {
// 任务队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

//  将任务添加到队列中
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }

// 执行线程
    public MyThreadPoll(int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                // 让线程从队列中消费任务，并进行执行
                try {
                    Runnable runnable = queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }


}


public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoll myThreadPoll = new MyThreadPoll(4);
        for (int i = 0; i < 1000; i++) {
            int id = i;
            myThreadPoll.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务" + id);
                }
            });

        }
    }

}
